package com.baseframe.tool.utils.redis;

import com.baseframe.tool.utils.spring.SpringUtil;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.StringRedisTemplate;

public class CommonRedisUtil {

    public static volatile StringRedisTemplate redisTemplate;

    // 获取RedisTemplate实例
    private static StringRedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            synchronized (CommonRedisUtil.class) {
                redisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
            }
        }
        return redisTemplate;
    }

    // 删除指定键的缓存
    public static boolean delete(String key) {
        Boolean delete = getRedisTemplate().delete(key);
        return delete == null || !delete ? Boolean.FALSE : Boolean.TRUE;
    }

    // 获取指定键的值
    public static String getValue(String key) {
        return getRedisTemplate().opsForValue().get(key);
    }

    // 设置指定键的值，并指定过期时间
    public static void setValue(String key, String value, Long timeout, TimeUnit timeUnit) {
        getRedisTemplate().opsForValue().set(key, value, timeout, timeUnit);
    }

    // 设置指定键的值
    public static void setValue(String key, String value) {
        getRedisTemplate().opsForValue().set(key, value);
    }

    // 获取指定键的过期时间
    public static long getExpirationTim(String key, TimeUnit timeUnit) {
        Long expire = getRedisTemplate().getExpire(key, timeUnit);
        if (expire == null) {
            expire = -2L;
        }
        return expire;
    }

    // 获取指定键的过期时间
    public static long getExpirationTime(String key) {
        Long expire = getRedisTemplate().getExpire(key);
        if (expire == null) {
            expire = -2L;
        }
        return expire;
    }

    // 设置指定键的哈希值
    public static void setHash(String key1, Object key2, Object value) {
        getRedisTemplate().opsForHash().put(key1, key2, value);
    }

    // 设置指定键的哈希值映射
    public static void setHashAll(String key, Map<Object, Object> map) {
        getRedisTemplate().opsForHash().putAll(key, map);
    }

    // 获取指定键的哈希值
    public static Object getHash(String key, Object field) {
        return getRedisTemplate().opsForHash().get(key, field);
    }
}
